import Vue from 'vue'
import VueRouter from 'vue-router'

import Main from '@/components/layout/Main.vue'
import Empty from '@/components/layout/Empty.vue'

//读取所有路由文件
const requireModules = require.context('@/pages', true, /\.vue$/);

/**
 * 获取文件路径
 * @param value
 * @returns {*}
 */
const getFilePath = function (value) {
    value = value.replace(/\.\//, "");
    value = value.replace(/\.vue/, "");
    return value;
}
let routerObject = {};
//遍历循环路由文件
requireModules.keys().forEach(file => {
    //获取组建信息
    let component = requireModules(file);
    let nameInfo = getFilePath(file).split('/');
    //初始化标题信息
    let meta = Object.assign({
        title: "默认标题",
        parentMenu: "",
        activeMenu: "",
        icon: "el-icon-eleme",
        keepAlive: false,
        hidden: false,
    }, component.default.meta || {});

    let router = {
        path: "/" + getFilePath(file),
        component: component.default,
        hidden: meta.hidden,
        name: component.default.name || nameInfo.join('_'),
        meta: meta
    }

    if (nameInfo.length === 1) {
        let mainName = nameInfo['0'];
        router.redirect = "/" + mainName + "/" + mainName;
        router.children = [];
        //存储数据
        routerObject[mainName] = router;
    }

    if (nameInfo.length === 2) {
        let mainName = nameInfo['0'];
        //排除components目录下的文件被加载
        if (mainName !== "components") {
            if (!routerObject[mainName]) {
                routerObject[mainName] = {
                    path: "/" + mainName,
                    component: Main,
                    name: component.name || nameInfo.join('_'),
                    redirect: "/" + mainName + "/" + mainName,
                    children: []
                }
            }
            //添加路由数据
            routerObject[mainName].children.push(router);
        }
    }
});

Vue.use(VueRouter);

//默认路由信息
const routes = [
    {
        path: '/',
        component: Empty,
        redirect: '/home/home',
        name: 'root',
        children: Object.values(routerObject)
    }
];

const router = new VueRouter({
    routes
})

export default router
